import 'package:enterprise_v6_app/app/components/custom_refresh.dart';
import 'package:enterprise_v6_app/app/components/toast_widget.dart';
import 'package:enterprise_v6_app/app/core/core.dart';
import 'package:enterprise_v6_app/app/core/http/http.dart';
import 'package:enterprise_v6_app/app/core/utils/interface.dart';
import 'package:enterprise_v6_app/app/core/utils/log_util.dart';
import 'package:enterprise_v6_app/app/data/api/person_apis.dart';
import 'package:enterprise_v6_app/app/data/entities/common/department_user_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/inspec/inspec_query_plan_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/inspec/query_all_department_locations_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/inspec/submit_task.dart';
import 'package:enterprise_v6_app/app/data/entities/inspec/task_department_list_entity.dart';

class ManageInspectionController extends GetxController {

  /// 列表刷新key
  final GlobalKey<CustomEasyRefreshListState> globalKey = GlobalKey();

  /// 右侧边栏
  final GlobalKey<ScaffoldState>  rightScaffoldKey = GlobalKey();

  // 任务是否提交
  bool isSubmitted = false;


  // 所有单元
  List<QueryAllDepartmentLocationsEntity> queryDeparList = [];

  // 选中的单元
  int selectDepar = 0;

  // 选择的任务id列表
  List<SubmitTask> selectTaskIdList = [];

  /// 分组后的list
  List<SubmitTimeList> timeList = [];


  // 输入的方案名称
  String inputSchemeName = '';

  /// 已有的方案
  List<InspecQueryPlanEntity>  alreadyPlan = [];

  // 选择的已有方案
  int? selectAlreadyPlan;


  // 是否加入已有方案
  bool isAddPlan = false;

  // 输入的任务名称
  String? taskName;

  /// 人员列表
  List<DepartmentUserEntity> personList = [];

  /// 选择的人员
  int? selectPerson;

  /// 查询任务列表单元
  /// [type] 是否查看所有 1：是  2：否
  void queryTaskList(int type) async {
    final response = await HttpUtil().generateGetRequest<List<QueryAllDepartmentLocationsEntity>>(
        Interface.getInspectionTaskList,
        queryParameters: {
          'isSystem': type,
        }
    ).execute();

    response.onSuccess((result) {
      if(result.data != null) {
        queryDeparList = result.data!;
        if(queryDeparList.length > 1) {
          globalKey.currentState?.onRefresh();
          selectTaskIdList.clear();
          update();
        }
      }

    });

  }

  /// 部门选择
  /// [add] 点击左按钮还是右按钮
  void selectDepartment(bool add) async {
    if (add) {
      if(selectDepar < (queryDeparList.length - 1)) {
        selectDepar = selectDepar + 1;
        globalKey.currentState?.onRefresh();
        selectTaskIdList.clear();
      }
    } else {
      if((selectDepar + 1)  > 1) {
        selectDepar = selectDepar - 1;
        globalKey.currentState?.onRefresh();
        selectTaskIdList.clear();
      }
    }

    update();
  }

  /// 点击展开
  clickExpand(TaskDepartmentListEntity item) {
    item.isExpanded = !item.isExpanded;
    update();
  }

  // 查询本部门所有任务
  Future<List<TaskDepartmentListEntity>> queryTaskListByDepartment({int num=  1,int? size = 20}) async {
    List<TaskDepartmentListEntity> list = [];
    if(queryDeparList.isNotEmpty && selectDepar != -1){
      final String? id = queryDeparList[selectDepar].id;
      final response = await HttpUtil().generateGetRequest<List<TaskDepartmentListEntity>>(
          Interface.getInspectionTaskListByScheme,
          queryParameters: {
            'pageNum' :num,
            'pageSize': size,
            'unitId' : id,
            'taskName': taskName,
          }
      ).execute();

      response.onSuccess((result) {
        if(result.data != null && result.data!.isNotEmpty) {
          list = result.data!;
          for(var i in list) {
            if(i.taskTimeNodeTables != null) {
              i.taskTimeNodeTables!.sort((a, b) => int.tryParse(a.startDate??'')!.compareTo(int.tryParse
                (b.startDate ?? '')!.toInt()));
            }
          }
        }
        update();
      });
      return list;
    } else {
      return [];
    }

  }

  /// 领取任务或撤销
  void taskClaim(TaskDepartmentListTaskTimeNodeTables item, int index) {
    if(item.currentRecipient) {
      // 撤销任务
      item.currentRecipient = false;
      selectTaskIdList.removeWhere((element) => element.id == item.id);
    } else {
      AppLogger.log(globalKey.currentState!.listData.toString());
      // 领取任务
      item.currentRecipient = true;
      selectTaskIdList.add(SubmitTask(
        id: item.id,
        taskName: (globalKey.currentState!.listData[index] as TaskDepartmentListEntity).troubleshootContent ,
        time: item.startDate,
      ));
    }

    update();
  }

  /// 提交按钮
  void submitButton() {
    if(isAddPlan) {
      addPlan();
    } else {
      submitTask();
    }
  }

  /// 提交方案
  void submitTask() async {

    if(inputSchemeName == '') {
      AppToast.showWarning('请输入方案名称');
      return;
    }

    final List<String?>  list = [];

    for(var i in selectTaskIdList) {
      list.add(i.id);
    }

    if(selectPerson == null) {
      AppToast.showWarning('请选择人员');
      return;
    }

    final data = {
      'createBy': '', // 创建人姓名
      'createById': '',  // 创建人id
      'createDate': '',
      'currentExecution': 0, //是否当前执行方案 1：是 2：不是
      'deleted': '',   // 0：正常 1：已删除
      'id': '',
      'ids': list,   // 时间节点任务的id集合
      'programmeName': inputSchemeName,  // 方案名称
      'remember': 2,   // 是否记住 1：不记住 2：记住
      'timeTaskIds': list.toString(),  // 时间节点任务id json字符串
      'updateBy': '',
      'updateById': '',
      'updateDate': '',
      'userId': personList[selectPerson!].id,    // 方案人员id
    };
    final res = await HttpUtil().generatePostRequest(Interface.getInspectionSchemeList,
      data: data,
    ).execute();

    res.onSuccess((result) {
      Get.back();
      clearData();
      globalKey.currentState?.onRefresh();
      AppToast.showSuccess('提交成功');
    });

  }

  /// 查询已有方案
  void queryAlreadyPlan() async {
    final res = await HttpUtil().generateGetRequest<List<InspecQueryPlanEntity>>(
      Interface.getInspectionSchemeListById,
    ).execute();

    res.onSuccess((result) {
      alreadyPlan = result.data!;
    });

  }

  /// 加入已有方案-分配处也可用
  void addPlan() async {
    final List<String?>  list = [];

    for(var i in selectTaskIdList) {
      list.add(i.id);
    }

    if(selectAlreadyPlan == null) {
      AppToast.showWarning('请选择方案');
      return;
    }

    if(selectPerson == null) {
      AppToast.showWarning('请选择人员');
      return;
    }

    final data = {
      'createBy': '', // 创建人姓名
      'createById': '',  // 创建人id
      'createDate': '',
      'currentExecution': 0, //是否当前执行方案 1：是 2：不是
      'deleted': '',   // 0：正常 1：已删除
      'id': alreadyPlan[selectAlreadyPlan!].id,
      'ids': list,   // 时间节点任务的id集合
      'programmeName': '',  // 方案名称
      'remember': 2,   // 是否记住 1：不记住 2：记住
      'timeTaskIds': list.toString(),  // 时间节点任务id json字符串
      'updateBy': '',
      'updateById': '',
      'updateDate': '',
      'userId':  personList[selectPerson!].id,    // 方案人员id
      'validityPeriodEndTime': '',
      'validityPeriodStartTime': ''
    };
    final res = await HttpUtil().generatePostRequest(Interface.getAddInspectionTaskListByScheme,
      data: data,
    ).execute();

    res.onSuccess((result) {
      Get.back();
      clearData();
      globalKey.currentState?.onRefresh();
      AppToast.showSuccess('加入成功');
    });
  }

  /// 查询部门人员
  void queryPerson() async {
    final res = await PersonApis.getUserAdmin().execute();
    res.onSuccess((result) {
      personList.addAll(result.data!);
    });
  }

  /// 选择完后清理数据
  void clearData() {
    isSubmitted = false;
    selectTaskIdList.clear();
    timeList.clear();
    update();
  }

  // 选择任务提交
  void selectTask() async {
    timeList.clear();
    if(selectTaskIdList.isNotEmpty) {
      /// 分组的map
      final Map<String, List<SubmitTask>> taskMap = {};

      /// 分组
      /// 用map的key来分组
      /// key为时间
      /// value为任务列表
      for (SubmitTask task in selectTaskIdList) {
        if (!taskMap.containsKey(task.time)) {
          taskMap[task.time!] = [];
        }
        taskMap[task.time]?.add(task);
      }
      // 转换为list
      timeList = taskMap.entries.map((entry) => SubmitTimeList(time: entry.key, tasks: entry.value)).toList();
      // 根据时间排序
      timeList.sort((a, b) => int.tryParse(a.time)?.compareTo(int.tryParse(b.time)?.toInt() ?? 0) ?? 0);
      isSubmitted = true;
      update();
    } else {
      AppToast.showWarning('请选择至少一个任务');
    }
    queryAlreadyPlan();
    queryPerson();
  }


  // 选择任务后取消
  void cancelTask() async {
    isSubmitted = false;
    update();
  }

  // 选择任务后移除任务
  void removeTask(int index,int taskIndex) async {
    if(timeList[index].tasks.isNotEmpty) {
      // 移除selectTaskIdList的相关数据
      selectTaskIdList.removeWhere((element) => element.id == timeList[index].tasks[taskIndex].id);
      timeList[index].tasks.removeAt(taskIndex);
    }
    if(timeList[index].tasks.isEmpty) {
      timeList.removeAt(index);
    }
    update();
  }

  // 清除选择数据
  clearSelected() {
    selectTaskIdList.clear();
  }

  // 是否加入已有方案
  void clickAddPlan(bool b) {
    isAddPlan = b;
    update(['dialog']);
  }

  // 输入任务名称后
  void inputTaskName(String? s) {
    taskName = s;
    globalKey.currentState?.onRefresh();
  }


  @override
  void onReady() {
    super.onReady();
    queryTaskList(1);
  }

}
